import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
// 你不需要' import app from './modules/app' '
// 它将自动要求所有vuex模块从模块文件
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

// 把从user getinfo获取的基础数据设置到对应state
const actions = {
  // 设置state store.commit('increment')
  set_basicsState: ({ commit, state }, data) => {
    const keyArr = Object.keys(data)
    keyArr.map(key => {
      if (key && key !== 'consumer') commit(`${key}/SET_INIT`, data[key], { root: true })
    })
  }
}

const store = new Vuex.Store({
  modules,
  getters,
  actions
})

export default store
